package main

import (
	"encoding/json"
	"encoding/xml"
	"io/ioutil"
	"os"
	"strings"

	"github.com/zsxm/scgo/chttplib"
	"github.com/zsxm/scgo/tools"
	"github.com/zsxm/scgo/tools/rsa"
)

const (
	configPath   = "C:/"
	configName   = "intranetConfig.xml"
	url          = "http://10.10.38.143/portal/addisclaimer/pc.html?template=addisclaimer&amp;tabs=pwd-sms"
	loginService = "http://10.10.38.143/portal/login.php"
)

//读取配置文件
func readConfig() (r *Config, err error) {
	var b []byte
	if checkFileIsExist(configPath + configName) {
		b, err = ioutil.ReadFile(configPath + configName)
		if err != nil {
			return nil, err
		}
	} else {
		_, err = os.Create(configPath + configName)
		if err != nil {
			return nil, err
		}
	}
	cfg := &Config{}
	err = xml.Unmarshal(b, cfg)
	if err != nil && err.Error() != "EOF" {
		return nil, err
	}
	return cfg, nil
}

//写配置文件
func writeConfig(cfg *Config) error {
	cfgByte, _ := xml.MarshalIndent(cfg, "", "\t")
	err := ioutil.WriteFile(configPath+configName, cfgByte, 07777)
	if err != nil {
		return err
	}
	return nil
}

//删除配置文件
func delConfig() (err error) {
	if checkFileIsExist(configPath + configName) {
		err = os.Remove(configPath + configName)
	}
	return err
}

//登录
func login(cfg *Config) (resJson, error) {
	mp := resJson{}
	err := writeConfig(cfg)
	if err != nil {
		return mp, err
	}
	rdPwd, err := decryptAndBase64Decode(cfg.Passwd)
	if err != nil {
		return mp, err
	} else {
		req := chttplib.Post(loginService)
		req.Param("rememberPwd", "0")
		req.Param("opr", "pwdLogin")
		req.Param("userName", cfg.LoginName)
		req.Param("pwd", string(rdPwd))

		res, err := req.String()
		if err != nil {
			return mp, err
		} else {
			res = strings.Replace(res, `'`, `"`, -1)
			res = strings.Replace(res, `pop`, `"pop"`, -1)
			res = strings.Replace(res, `<br>`, ` `, -1)
			err = json.Unmarshal([]byte(res), &mp)
			if err != nil {
				return mp, err
			}
		}
	}
	return mp, nil
}

//加密 字符串先rsa encrypt 后 Base64Decode
func encryptAndBase64Encode(b []byte) ([]byte, error) {
	var r []byte
	var err error
	r, err = rsa.Encrypt(b, publicKey)
	if err != nil {
		return r, err
	}
	r = tools.Base64Encode(r)
	return r, nil
}

//解密 字符串先Base64Decode 后 rsa decrypt
func decryptAndBase64Decode(b []byte) ([]byte, error) {
	var r []byte
	var err error
	r, err = tools.Base64Decode(b)
	if err != nil {
		return r, err
	}
	r, err = rsa.Decrypt(r, privateKey)
	if err != nil {
		return r, err
	}
	return r, nil
}

//检查文件是否存在
func checkFileIsExist(filename string) bool {
	exist := true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}

type resJson struct {
	Success  bool
	Msg      string
	UserName string
}

type Config struct {
	LoginName      string `xml:"loginName"`
	Passwd         []byte `xml:"passwd"`
	AutomaticLogin bool   `xml:"automaticLogin"`
}

var (
	publicKey = []byte(`-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEXHOEh6UVjfNDyUeOBV634Y+8
JrvDOjgyZz53oR33jYzYlhiJTTcmSo6iGYZ6s+jpGxKkVGGd4rzudNKQbLQb3VW/
HRDON8lfBNHhcmTSbI1tA9oW+Xd/tmjlV8joFmdv2HW6zYoKIwsx47LP/0SVHD+P
KCpLaBlBKhekMaYvowIDAQAB
-----END PUBLIC KEY-----`)

	privateKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDEXHOEh6UVjfNDyUeOBV634Y+8JrvDOjgyZz53oR33jYzYlhiJ 
TTcmSo6iGYZ6s+jpGxKkVGGd4rzudNKQbLQb3VW/HRDON8lfBNHhcmTSbI1tA9oW
+Xd/tmjlV8joFmdv2HW6zYoKIwsx47LP/0SVHD+PKCpLaBlBKhekMaYvowIDAQAB
AoGAZveL4801dg4PqFYd3Y1XU9lGBAXTo9YdreCR0y17h1qEpvZeO3FwH/YswTfd
Wu6IjeQSbHWLEr3ZELnVyMIX1zAegOjf4h8s46negfyVSDeTjWwMPQUiADW6B8jq
fjsY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